import os
import cgi
import datetime
import logging
import urllib
import wsgiref.handlers

from google.appengine.api import mail, memcache, users, xmpp
from google.appengine.ext.webapp import template
from google.appengine.api import mail, memcache, users
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

openIdProviders = (
    'Google.com/accounts/o8/id', # shorter alternative: "Gmail.com"
    'Yahoo.com',
    'MySpace.com',
    'AOL.com',
    'MyOpenID.com',
    # add more here
)


class Greeting(db.Model):
  """Models an individual Guestbook entry with an author, content, and date."""
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)
  vote = db.IntegerProperty(default=1,required=True)
  title = db.StringProperty(multiline=False)
  condition = db.StringProperty()
  yearmade = db.StringProperty()
  sellprice = db.StringProperty()
  photo = db.BlobProperty()
  category = db.StringProperty()   
  INDEX_ONLY = ['author', 'content'] 

  
  
user = users.get_current_user()
is_existing_user = Greeting.all().filter('author = ', user).get()
  
class Response(db.Model):
  """Allows responses to comments"""
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  inquiry = db.StringProperty()
  date = db.DateTimeProperty(auto_now_add=True)
  vote = db.IntegerProperty(default=1,required=True)
  idea = db.ReferenceProperty(Greeting,required=True)
 
class Selling(db.Model):
  """Selling an item"""
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)
  category = db.StringProperty()

class Profile(db.Model):
  """Models a user Profile"""
  date = db.DateTimeProperty(auto_now_add=True)
  author = db.UserProperty()
#  firstName = db.StringProperty(verbose_name='First Name',required=True)
#  lastName = db.StringProperty(verbose_name='Last Name',required=True)
  email = db.EmailProperty()
  content = db.StringProperty()
  profilePhoto = db.Blob()

class Professor(db.Model):
  """Models Professor Rating System"""
  date = db.DateTimeProperty(auto_now_add=True)
  author = db.UserProperty()
#  firstName = db.StringProperty(verbose_name='First Name',required=True)
#  lastName = db.StringProperty(verbose_name='Last Name',required=True)
  email = db.EmailProperty()
  content = db.StringProperty()
  profilePhoto = db.Blob()  
  
def professors_key(professors_name=None):
  """Constructs a datastore key for a Professors entity with professors_name."""
  return db.Key.from_path('Professors', professors_name or 'default_professors')
  
def profiles_key(profiles_name=None):
  """Constructs a datastore key for a Profile entity with profiles_name."""
  return db.Key.from_path('Profiles', profiles_name or 'default_profiles')
 
def guestbook_key(guestbook_name=None):
  """Constructs a datastore key for a Guestbook entity with guestbook_name."""
  return db.Key.from_path('Guestbook', guestbook_name or 'default_guestbook')

def selling_key(selling_name=None):
  """Constructs a datastore key for a Selling entity with guestbook_name."""
  return db.Key.from_path('Selling', selling_name or 'default_guestbook')
  
def existing_user(user):
  is_existing_user = UserProfile.all().filter('UserID = ', user).get()
  
def total_comments(user):
  count = Greeting.all().filter('author =', user).count(10000)
  
  if count >= 10000:
    count = "Infinity"
  return count  
  
def highest_votes():
  top_msu = Greeting.all().ancestor(guestbook_key()).order('-vote').filter("category =", 'MSU').fetch(3)
  return top_msu
  
def most_popular_category(category):
  #totalvotesincategory = Greeting.all().filter('author =', user).count(10000)
  
  if totalvotesincategory >= 100000:
    totalvotesincategory = "Top Category"
  return totalvotesincategory
  
def highest_rated_user(user):
  #totalvotesperuser = Greeting.all().filter('author =', user).count(10000)
  
  if totalvotesperuser >= 100000:
    totalvotesperuser = "Top User"
  return totalvotesperuser
 
class MainPage(webapp.RequestHandler):
    def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if s == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-date')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "" and s == "":
          greetings_query = greetings_query.filter("category =", c)
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else '',
            's': self.request.get('s') if '' != self.request.get('s') else '',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))
       
        
class Guestbook(webapp.RequestHandler):
  def post(self):
    maxlength=300
    if len(self.request.get("content")) > maxlength:
      self.error(400)
      return
    
      
    # We set the same parent key on the 'Greeting' to ensure each greeting is in
    # the same entity group. Queries across the single entity group will be
    # consistent. However, the write rate to a single entity group should
    # be limited to ~1/second.
    c = self.request.get('category')
    guestbook_name = self.request.get('guestbook_name')
    s = self.request.get('s')
    n = self.request.get('n')
    # To create new categories, comment out these lines below and add the
    # textbox back to the index.html file.
    #greetings = Greeting.all().fetch(1000)
    #categories = []
    #for greeting in greetings:
    #  categories.append(greeting.category)
    #if not c in categories:
    #  self.redirect('/hacks/hacker1.html')
    #  return
    # To create new categories, comment out the above lines
    
    greeting = Greeting(category=c, parent=guestbook_key(guestbook_name))  

    if users.get_current_user():
      greeting.author = users.get_current_user()        
      greeting.content = self.request.get('content')
      greeting.title = self.request.get('title')
      greeting.condition = self.request.get('condition')
      greeting.sellprice = self.request.get('sellprice')
      greeting.yearmade = self.request.get('yearmade')
      photo = images.resize(self.request.get('photo'), 400, 400)
      category = self.request.get('category')
      greeting.photo = db.Blob(photo)
      greeting.put()
      if s == "buyandsell":
        self.redirect('/?s=buyandsell'+'&c='+c)
      elif s == "feedback":
        self.redirect('/?s=feedback&c=cars')
      elif s == "profile":
        self.redirect('/?s=profile&c=mopeds')
      else:
        self.redirect('/college/buyandsell?c=')
    else:
      self.redirect(users.create_login_url('/?' + urllib.urlencode({'guestbook_name': guestbook_name})))

class Image (webapp.RequestHandler):
    def get(self):
      greeting = db.get(self.request.get("img_id"))
      if greeting.photo:
          self.response.headers['Content-Type'] = "CorrectMimeType"
          self.response.out.write(greeting.photo)
      else:
          self.error(404)
      
class Profiles(webapp.RequestHandler):
  def post(self):
    profiles_name = self.request.get('profiles_name')
    profile = Profile(parent=profiles_key(profiles_name))
    
    if users.get_current_user():
      profile.author = users.get_current_user()
      
    profile.content = self.request.get('content')
    profile.put()
    self.redirect('/?s=profile')

class Professors(webapp.RequestHandler):
  def post(self):
    professors_name = self.request.get('professors_name')
    professor = Professor(parent=professors_key(professors_name))
    
    if users.get_current_user():
      professor.author = users.get_current_user()
      
    professor.content = self.request.get('content')
    professor.put()
    self.redirect('/?s=profratings')
	  
class Sellitem(webapp.RequestHandler):
  def post(self):
    maxlength=140
    if len(self.request.get("content")) > maxlength:
      self.error(400)
      return
    c = self.request.get('category')
    selling_name = self.request.get('selling_name')
    s = self.request.get('s')

    selling = Selling.all().fetch(1000)

    if user.get_current_user():
      selling.author = users.get_current_user()
      selling.content = self.request.get('content')
      selling.put()
      self.redirect('/?s=buyandsell'+'&c='+c)
    else:
      self.redirect(users.create_login_url('/?' + urllib.urlencode({'message_name': message_name})))
     
class GuestbookDeleter(webapp.RequestHandler):
  def post(self):
    guestbook_name = self.request.get('guestbook_name')
    user = users.get_current_user()
    c = self.request.get('category')
    guestbook_name = self.request.get('guestbook_name')
    s = self.request.get('s')	
    if user:
      greeting_id = self.request.get('greeting_id_delete')
      greeting_id = int(greeting_id, 10)
      logging.info('trying to delete greeting id#' + str(greeting_id))
      greeting = Greeting.get_by_id(greeting_id, guestbook_key())
      logging.info('found greeting id#' + str(greeting))
      logging.info('logged in user is ' + str(user) + ' and greeting author is ' + str(greeting.author))
      logging.info('are the usernames the same? ' + str(str(user) == str(greeting.author)))
      if greeting != None: 
        logging.info('the greeting was found')
        if user.user_id() == greeting.author.user_id():
          logging.info('about to delete greeting id#' + str(greeting_id))
          greeting.delete()
          logging.info('deleted greeting id#' + str(greeting_id))
          self.redirect('/myprofile/messages')
        else:
          self.redirect('/hacks/hacker3.html')
      else:
        self.redirect('/hacks/hacker2.html')
    else:
      self.redirect('/hacks/hacker1.html')
      
class SpinUp(webapp.RequestHandler):
  
  def post(self):
    guestbook_name = self.request.get('guestbook_name')
    user = users.get_current_user()
    if user:
      greeting_id = self.request.get('greeting_id_up')
      greeting_id = int(greeting_id, 10)
      logging.info('trying to spin up greeting id#' + str(greeting_id))
      greeting = Greeting.get_by_id(greeting_id, guestbook_key())
      if greeting:
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) + 1
        greeting.put()
        self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))
      else:
        self.redirect('/hacks/hacker2!!!.html')
      if int(greeting.vote) > 10 and int(greeting.vote) < 50 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) + 1
        greeting.put()
      elif int(greeting.vote) > 50 and int(greeting.vote) < 100 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) + 4
        greeting.put()
      elif int(greeting.vote) == 101 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) + 19
        greeting.put()
      elif int(greeting.vote) > 101 and int(greeting.vote) < 1000 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) + 9
        greeting.put()
    else:
      self.redirect(users.create_login_url('/?' + urllib.urlencode({'guestbook_name': guestbook_name})))
    
class SpinDown(webapp.RequestHandler):
  def post(self):
    guestbook_name = self.request.get('guestbook_name')
    user = users.get_current_user()
    if user:
      greeting_id = self.request.get('greeting_id_down')
      greeting_id = int(greeting_id, 10)
      logging.info('trying to spin up greeting id#' + str(greeting_id))
      greeting = Greeting.get_by_id(greeting_id, guestbook_key())
      if greeting:
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) - 1
        greeting.put()
        self.redirect('/?' + urllib.urlencode({'guestbook_name': guestbook_name}))
      else:
        self.redirect('/hacks/hacker2!!!.html')
      if int(greeting.vote) > 10 and int(greeting.vote) < 50 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) - 1
        greeting.put()
      elif int(greeting.vote) > 50 and int(greeting.vote) < 100 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) - 4
        greeting.put()
      elif int(greeting.vote) == 101 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) - 19
        greeting.put()
      elif int(greeting.vote) > 101 and int(greeting.vote) < 1000 :
        logging.info('found greeting id#' + str(greeting_id))
        greeting.vote = (greeting.vote or 0) - 9
        greeting.put()
    else:
      self.redirect(users.create_login_url('/?' + urllib.urlencode({'guestbook_name': guestbook_name})))
            
      
class Respond(webapp.RequestHandler):
  def post(self):
    guestbook_name = self.request.get('guestbook_name')
    user = users.get_current_user()
    c = self.request.get('category')
    s = self.request.get('s')	
    if user:
      greeting_id = self.request.get('greeting_id_respond')
      greeting_id = int(greeting_id, 10)
      logging.info('trying to spin up greeting id#' + str(greeting_id))
      greeting = Greeting.get_by_id(greeting_id, guestbook_key())
      if greeting:
        response = Response(idea = greeting)
        response.author = users.get_current_user()
        response.content = self.request.get('content')
        response.inquiry = self.request.get('inquiry')
        #mail.send_mail(
        #    user.email(), # from
        #    greeting.author.email(), # to
        #    'MSUchat: %s is %s - %s' % (user, response.inquiry, greeting.title), # subj
        #   'You received a response to your posting.\r\n\r\n%s wrote:\r\n\r\n"%s"' % (user, response.content), # body
        #)
        response.put()      
        self.redirect('/college/buyandsell')
      else:
        self.redirect('/hacks/hacker4.html')
    else:
      self.redirect(users.create_login_url('/?' + urllib.urlencode({'guestbook_name': guestbook_name})))
    
class UserProfileHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'user.html')
        self.response.out.write(template.render(path, template_values))

class ProfessorRatingsHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'profratings.html')
        self.response.out.write(template.render(path, template_values))

class CollegeHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'college.html')
        self.response.out.write(template.render(path, template_values))        
        
class ClubsHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'clubs.html')
        self.response.out.write(template.render(path, template_values))

class MessagesHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'messages.html')
        self.response.out.write(template.render(path, template_values))

class BuyandsellHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'buyandsell.html')
        self.response.out.write(template.render(path, template_values))        
        
class EditHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'edit.html')
        self.response.out.write(template.render(path, template_values))

class AccountHandler(webapp.RequestHandler):
   def get(self):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'account.html')
        self.response.out.write(template.render(path, template_values))

class CategoryHandler(webapp.RequestHandler):
   def get(self, user):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'buyandsell.html')
        self.response.out.write(template.render(path, template_values))    

class UserItemHandler(webapp.RequestHandler):
   def get(self, category, user):
        guestbook_name=self.request.get('guestbook_name')        
        greetings_query = None
        profiles_name=self.request.get('profiles_name')
        profiles_query = Profile.all().ancestor(profiles_key(profiles_name)).order('-date')
        profiles = profiles_query.fetch(1)
        professors_name=self.request.get('professors_name')
        professors_query = Professor.all().ancestor(professors_key(professors_name)).order('-date')
        professors = profiles_query.fetch(30)        
        selling_name=self.request.get('selling_name')
        selling_query = Selling.all().ancestor(selling_key(selling_name)).order('-date')
        n = self.request.get('n')
        s = self.request.get('s')
        logging.info("s=" + str(s))        
        user = users.get_current_user() 
        
        if n == "oldest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')
        elif n == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('date')
        
        if s == "newest":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')          
        elif s == "me":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote')
        elif s == "profile":
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).filter('author =', users.get_current_user()).order('-vote') 
        else:
          greetings_query = Greeting.all().ancestor(guestbook_key(guestbook_name)).order('-date')

        c = self.request.get('c')
        if c != "":
          greetings_query = greetings_query.filter("category =", c).order('-date')
    
        allselling = selling_query.fetch(10)
        totalselling = Selling.all()

        profiles = Profile.all()
        profiles.ancestor(profiles_key(profiles_name))
        profiles.filter("author =", users.get_current_user())
        profiles.order("-date")
        
        professors = Professor.all()
        professors.ancestor(professors_key(professors_name))
        professors.filter("author =", users.get_current_user())
        professors.order("-date")        
        
        allGreetings = Greeting.all()    
        greetings = greetings_query.fetch(30)        
        allGreetings = Greeting.all().fetch(1000)
        categories = []
        for greeting in allGreetings:
          categories.append(greeting.category)
        categories = set(categories)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Connect with Google+'
            
        template_values = {
            'greetings': greetings,
            'profiles': profiles,
            'professors': professors,
            'categories': categories,
            'allselling': allselling,
            'url': url,
            'url_linktext': url_linktext,
            'user': users.get_current_user(),
			      'logged_in': users.get_current_user() != None,
            'c': self.request.get('c') if '' != self.request.get('c') else 'choosecategory',
            's': self.request.get('s') if '' != self.request.get('s') else 'home',
            'n': self.request.get('n') if '' != self.request.get('n') else '',
            'personal_comment_count': total_comments(users.get_current_user()),
            'top_msu': highest_votes(),
        }

        path = os.path.join(os.path.dirname(__file__), 'items.html')
        self.response.out.write(template.render(path, template_values))    
        
application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/sign', Guestbook),
  ('/profile', Profiles),
  ('/professor', Professors),
  ('/img', Image),
  ('/myprofile', UserProfileHandler),
  ('/myprofile/messages', MessagesHandler),
  ('/myprofile/edit', EditHandler),
  ('/myprofile/account', AccountHandler),
  ('/college', CollegeHandler),
  ('/college/clubs', ClubsHandler),
  ('/college/profratings', ProfessorRatingsHandler),
  ('/college/buyandsell', BuyandsellHandler),
  (r'/college/buyandsell/(.*)', CategoryHandler), 
  (r'/college/(.*)/(.*)', UserItemHandler),   
  ('/deleter', GuestbookDeleter),
  ('/spinup', SpinUp),
  ('/spindown', SpinDown),
  ('/respond', Respond),
  ('/selling', Selling),
 ], debug=True)


def main():
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
